package logic

import (
	"context"
	"errors"
	"videos/model/cache"
	"videos/model/mysql"
	"videos/pkg"
	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if in.LoginType == 1 {
		err := user.FindUserByMobile(mysql.DB, in.Mobile)
		if err != nil {
			return nil, err
		}

		if user.ID == 0 {
			return nil, errors.New("该用户未注册,请先注册")
		}

		result, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if result != in.SmsCode {
			return nil, errors.New("短信验证码错误")
		}
	}

	if in.LoginType == 2 {
		err := user.FindUserByMobile(mysql.DB, in.Mobile)
		if err != nil {
			return nil, err
		}

		if user.ID == 0 {
			return nil, errors.New("该用户未注册,请先注册")
		}

		if pkg.Md5(in.Password) != user.Password {
			return nil, errors.New("密码错误")
		}
	}

	return &videorpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
